<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--范畴数据-->
            <el-col :span="3" :xs="20" style="border-width: 1px">
                <div style="height: 900px;overflow:scroll;">
                    <div v-for="dict in dict.type.ex_question_topic_dict" class="topic_div">
                        <el-link :underline="false" class="topic_link" :type="queryParams.topic == dict.value ? 'danger' : 'primary'" @click="topicChange(dict)">
                            {{ dict.label }}
                        </el-link>
<!--                        <el-link :underline="false" :type="queryParams.topic == dict.value ? 'danger' : 'info'" @click="topicChange(dict)">{{ dict.label }}</el-link>-->
                    </div>
                </div>
            </el-col>
            <!--题目数据-->
            <el-col :span="21" :xs="24">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                    <el-form-item label="科目" prop="subject">
                        <el-select v-model="queryParams.subject" placeholder="请选择科目" clearable>
                            <el-option v-for="dict in dict.type.ex_question_subject_dict" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="内容" prop="content">
                        <el-input v-model="queryParams.content" placeholder="请输入内容" clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['ex:question:add']">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['ex:question:edit']">修改</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['ex:question:remove']">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="info" plain icon="el-icon-upload" size="mini" @click="upload.open = true" v-hasPermi="['ex:question:import']">导入</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="warning" plain :icon="cache_icon" size="mini" @click="flushCache" v-hasPermi="['ex:question:cache']">刷新缓存</el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>

                <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange" :height="table_height">
                    <el-table-column type="selection" width="55" align="center"/>
                    <el-table-column label="范畴" align="center" prop="topic" width="130">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.ex_question_topic_dict" :value="scope.row.topic"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="科目" align="center" prop="subject" width="130">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.ex_question_subject_dict" :value="scope.row.subject"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="类型" align="center" prop="type" width="130">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.ex_question_type_dict" :value="scope.row.type"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="内容" align="center" prop="content"/>
                    <el-table-column label="答案(绿色为答案)" align="center" prop="exQuestinOptionList" width="200">
                        <template slot-scope="scope">
                            <p v-for="item in scope.row.exQuestinOptionList" :class="item.right ? 'text_1' : 'text_2'">{{ item.index }}：{{item.content}}</p>
                        </template>
                    </el-table-column>
                    <el-table-column label="分析" align="center" prop="info"/>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ex:question:edit']">修改</el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['ex:question:remove']">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>
            </el-col>
        </el-row>


        <!-- 添加或修改题目表对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="80px">
                <el-tabs v-model="formActive">
                    <el-tab-pane label="基本信息" name="1">
                        <el-form-item label="范畴" prop="topic">
                            <el-select v-model="form.topic" placeholder="请选择范畴" clearable>
                                <el-option v-for="dict in dict.type.ex_question_topic_dict" :key="parseInt(dict.value)" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="科目" prop="subject">
                            <el-select v-model="form.subject" placeholder="请选择科目" clearable>
                                <el-option v-for="dict in dict.type.ex_question_subject_dict" :key="parseInt(dict.value)" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="类型" prop="type">
                            <el-radio-group v-model="form.type">
                                <el-radio v-for="dict in dict.type.ex_question_type_dict" :key="parseInt(dict.value)" :label="parseInt(dict.value)">{{ dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="问题及答案" name="2">
                        <div style="float: left;width: 300px">
                            <el-form-item label="问题" prop="content">
                                <el-input type="textarea" v-model="form.content" rows="12" placeholder="请输入内容" style="width: 300px"/>
                            </el-form-item>
                        </div>
                        <div style="width: 500px;float:left;margin-left: 10px;">
                            <el-form-item label="答案选项 (勾选项为答案)" prop="exQuestinOptionList">
                                <el-table :data="form.exQuestinOptionList" ref="exQuestinOption" empty-text="请在下方输入选项添加" :show-header="false" style="width: 100%">
                                    <el-table-column width="35">
                                        <template slot-scope="scope"><el-checkbox v-model="scope.row.right"/></template>
                                    </el-table-column>
                                    <el-table-column label="序号" prop="index" width="35"/>
                                    <el-table-column label="内容" prop="content">
                                        <template slot-scope="scope">
                                            <el-input v-if="scope.row.edit" v-model="scope.row.content" style="width: 100%"/>
                                            <span v-else>{{scope.row.content}}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column>
                                        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                                            <template slot-scope="scope">
                                                <el-tooltip class="item" effect="dark" content="删除" placement="top-end">
                                                    <el-button size="mini" type="text" icon="el-icon-delete" @click="$delete(form.exQuestinOptionList,scope.$index)"></el-button>
                                                </el-tooltip>
                                                <el-tooltip v-if="scope.row.edit" class="item" effect="dark" content="完成" placement="top-start">
                                                    <el-button size="mini" type="text" icon="el-icon-circle-check" @click="scope.row.edit = false"></el-button>
                                                </el-tooltip>
                                                <el-tooltip v-else class="item" effect="dark" content="修改" placement="top-start">
                                                    <el-button size="mini" type="text" icon="el-icon-edit" @click="scope.row.edit = true"></el-button>
                                                </el-tooltip>
                                            </template>
                                        </el-table-column>
                                    </el-table-column>
                                </el-table>
                            </el-form-item>
                            <el-input placeholder="请输入添加的选项" v-model="optionFlag" size="small">
                                <template slot="append">
                                    <el-button slot="append" icon="el-icon-plus" @click="handleAddExQuestinOption">添加</el-button>
                                </template>
                            </el-input>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="题库解析" name="3">
                        <el-form-item label="分析" prop="info">
                            <el-input v-model="form.info" type="textarea" placeholder="请输入内容" style="width: 700px" rows="12"/>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 题目表导入对话框 -->
        <el-dialog title="导入题目" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
                       :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listQuestion, delQuestion, addQuestion, updateQuestion, flushCache, flush_cache} from "@/api/ex/question";
import {copyObj} from "@/utils/zzDouUtils/objUtil";
import {fillNode,isEmptyArr} from "@/utils/zzDouUtils/arrayUtil";
import {getToken} from "@/utils/auth";
import {nowDateStr} from "@/utils/zzDouUtils/dateUtil";

export default {
    name: "Question",
    dicts: ['ex_question_subject_dict', 'ex_question_topic_dict', 'ex_question_type_dict'],
    data() {
        return {
            formActive: '1',
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 子表选中数据
            checkedExQuestinOption: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 题目表表格数据
            questionList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 是否正确时间范围
            daterangeCreateTime: [],
            cache_icon: 'el-icon-refresh',//刷新缓存图标
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                topic: null,
                subject: null,
                content: null,
                type: null,
                info: null,
                reservedOne: null,
                reservedTwo: null,
            },
            // 表单参数
            form: {},
            optionFlag:null,
            // 表单校验
            rules: {
                topic:[
                    {required: true, message: "请选择范畴", trigger: "blur"},
                ],
                subject:[
                    {required: true, message: "请选择科目", trigger: "blur"},
                ],
                type:[
                    {required: true, message: "请选择类型", trigger: "blur"},
                ],
                content:[
                    {required: true, message: "内容不可为空", trigger: "blur"},
                ],
                exQuestinOptionList:[
                    { type: 'array', required: true, message: "至少需要两个选项", trigger: "blur" }
                ]
            },
            // 导入参数
            upload: {
                // 是否显示弹出层
                open: false,
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的学生数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: {Authorization: "Bearer " + getToken()},
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/ex/question/importData"
            },
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询题目表列表 */
        getList() {
            this.loading = true;
            this.queryParams.params = {};
            if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
                this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
                this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
            }
            listQuestion(this.queryParams).then(response => {
                this.questionList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        /** 范畴改变事件 */
        topicChange(dict){
          this.queryParams.topic = dict.value;
          this.getList();
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        /** 刷新缓存 */
        flushCache(){
            this.cache_icon = 'el-icon-loading';
            flush_cache().then(response=>{
                this.$notify.success({title: "刷新缓存",message: "刷新缓存成功"});
                this.cache_icon = 'el-icon-refresh';
            })
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                topic: null,
                subject: null,
                content: null,
                type: null,
                info: null,
                reservedOne: null,
                reservedTwo: null,
                createTime: null,
                exQuestinOptionList: [],
            };
            this.resetForm("form");
            this.formActive = "1";
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeCreateTime = [];
            this.resetForm("queryForm");
            this.queryParams.topic = null;
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加题目";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.form = copyObj(row);
            this.form.exQuestinOptionList = fillNode(this.form.exQuestinOptionList,'edit',false);
            this.open = true;
            this.title = "修改题目";
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    //校验
                    if (isEmptyArr(this.form.exQuestinOptionList)){
                        return;
                    }
                    if (this.form.exQuestinOptionList.length < 2){
                        this.$notify.warning({title: "选项",message: "至少需要两个选项"});return;
                        return;
                    }
                    var flag = 0;
                    for (let i = 0; i < this.form.exQuestinOptionList.length; i++) {
                        if (this.form.exQuestinOptionList[i].right) flag++;
                    }
                    if (this.form.type === 1){//单选
                        if (flag!==1){
                            this.$notify.warning({title: "单选题",message: "至少且只需要一个答案"});return;
                        }
                    }else{//多选
                        if (flag<2){
                            this.$notify.warning({title: "多选题",message: "至少需要两个答案"});return;
                        }
                    }
                    if (this.form.id != null) {
                        updateQuestion(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addQuestion(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除题目表编号为"' + ids + '"的数据项？').then(function () {
                return delQuestion(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 题目选项表添加按钮操作 */
        handleAddExQuestinOption() {
            if (this.optionFlag == null || this.optionFlag == undefined || this.optionFlag==''){
                this.$notify.warning({title: "内容",message: "不可为空"});
                return;
            }
            if (this.form.exQuestinOptionList == undefined || this.form.exQuestinOptionList == null){
                this.form.optionList = [];
            }
            let obj = {
                index: String.fromCharCode(64 + this.form.exQuestinOptionList.length + 1),
                content: this.optionFlag,
                right: false,
                edit: false,
            };
            this.form.exQuestinOptionList.push(obj);
            this.optionFlag = null;
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('ex/question/export', {
                ...this.queryParams
            }, `题目_${nowDateStr()}.xlsx`)
        },
        /** -------- 导入 -------- */
        /** 下载模板操作 */
        importTemplate() {
            this.download('ex/question/importTemplate', {}, `题目模板_${nowDateStr()}.xlsx`)
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
    }
};
</script>
<style>
.el-input-group__append {
    background-color: #409EFF;
    color: white;
}
.text_1{
    color: #67C23A;
    font-weight:bold;
    padding: 0;
    margin: 0;
}
.text_2{
    padding: 0;
    margin: 0;

}

.topic_div{
    width: 30%;
    height: 90px;
    float: left;
    background: #EBEEF5;
    margin-right: 3px;
    margin-bottom: 3px;
    text-align: center;
    overflow: auto;
    border-radius: 6px; /* 圆角 */
}
.topic_link{
    width: 100%;
    height: 100%;
    margin: 0;
}
</style>
